package com.szq.day39.controller;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.szq.day39.Exception.BusinessException;
import com.szq.day39.biz.BlogBiz;
import com.szq.day39.entity.Blog;
import com.szq.day39.entity.Users;

@Controller
@RequestMapping("/blog")
public class BlogController {
	@Resource
	private BlogBiz biz;
	
	@RequestMapping("/list")
	public String list(Map<String, Object> request) throws BusinessException{
		request.put("list", biz.findAll());
		return "/blog/list";
	} 
	
	@RequestMapping("/add")
	public String add(Blog blog,HttpSession session) throws BusinessException{
		Users user = (Users) session.getAttribute("currentUser");
		blog.setUser(user);
		biz.save(blog);
		return "redirect:/blog/list";
	}
	
	@RequestMapping("/delete/{blogId}")
	public String delete(@PathVariable("blogId") int blogId) throws BusinessException{
		Blog blog =biz.findById(blogId);
		if(blog==null){
			throw new BusinessException("B02C02");
		}
		biz.delete(blog);
		return "redirect:/blog/list";
	}
	
	@RequestMapping("/update")
	public String update(Blog blog) throws BusinessException{
		Blog oldBlog =biz.findById(blog.getBlogId());
		oldBlog.setBlogContent(blog.getBlogContent());
		biz.update(oldBlog);
		return "redirect:/blog/list";
	}
	
	@RequestMapping("/preAdd")
	public String preAdd(){
		return "/blog/add";
	}
	@RequestMapping("/preUpdate/{blogId}")
	public String preUpdate(@PathVariable("blogId") int blogId,Map<String, Object> request) throws BusinessException{
		Blog blog =biz.findById(blogId);
		if(blog==null){
			throw new BusinessException("B02C03");
		}
		request.put("blog",blog);
		return "/blog/update";
	}
	
	@RequestMapping("/detail/{blogId}")
	public String detail(@PathVariable("blogId") int blogId,Map<String, Object> request) throws BusinessException{
		Blog blog =biz.findById(blogId);
		if(blog==null){
			throw new BusinessException("B02C04");
		}
		request.put("blog",blog);
		return "/blog/detail";
	}

}
